import { memo } from "react"
import styled from "@emotion/styled"
import { useCallback, useEffect, useState } from "react"
import { SvgComponent } from "@/components/base/Svg"

const ButtonTop = styled.a`
    position: fixed;
    z-index: 999;
    right: 20rem;
    bottom: 100rem;
    width: 34rem;
    height: 34rem;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    opacity: 0.8;
    background: linear-gradient(180deg, #ff676d 0%, #ff75af 100%);
    transform: translateY(150rem);
    transition: transform 0.3s linear;
    &.show {
        transform: translateY(0);
    }
`

const IconReceiveSvg = styled(SvgComponent("plan_up.svg"))`
    width: 20rem;
`

const Component: React.FC = () => {
    const [showTop, setShowTop] = useState(false)

    useEffect(() => {
        // 定义滚动事件处理函数
        const handleScroll = () => {
            const scrollPosition = window.scrollY
            const screenHeight = window.innerHeight
            if (scrollPosition > screenHeight) {
                setShowTop(true)
            } else {
                setShowTop(false)
            }
        }

        // 监听滚动事件
        window.addEventListener("scroll", handleScroll)

        // 在组件卸载时移除事件监听器
        return () => {
            window.removeEventListener("scroll", handleScroll)
        }
    }, [])

    const scrollToTop = useCallback(() => {
        window.scrollTo({
            top: 0,
            left: 0,
            behavior: "smooth",
        })
    }, [])

    return (
        <ButtonTop
            onClick={scrollToTop}
            className={showTop ? "show" : undefined}
        >
            <IconReceiveSvg />
        </ButtonTop>
    )
}

export default memo(Component)
